package com.huisou.basedataservice;

import com.huisou.domain.JobType;
import com.huisou.orm.HibernateDao;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

/**
 * 状态0为有效
 * 
 * @author Jack
 * 
 */
@Repository
public class JobTypeDao extends HibernateDao<JobType, Integer> {
	
	protected Logger				log				= LoggerFactory.getLogger(getClass());
	
	private final String			hql				= "select new JobType(id ,name) from JobType where parentId=? and status=0 order by orderNo asc ";
	private final String			selectroothql	= "select new JobType(id ,name) from JobType where parentId IS NULL and status=0 order by orderNo asc ";
	
	@Resource
	RedisTemplate<String, Object>	redisTemplate;
	@Resource
	private StringRedisTemplate		stringRedisTemplate;
	
	/**
	 * 根据父类ID，获取职位类别
	 * 
	 * @param parentId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<JobType> getListByParentId(Integer parentId, boolean isroot) {
		String key = RedisConstants.KEY_JOBTYPE_LIST_PID + "_" + parentId;
		
		List<JobType> listJobTypes = null;
		try {
			listJobTypes = (List<JobType>) redisTemplate.opsForValue().get(key);
		}
		catch (Exception e) {
			log.error("获取父类ID为{}的职位类别列表出错.", parentId);
		}
		if (listJobTypes == null) {
			try {
				if (isroot) {
					listJobTypes = find(selectroothql);
				}
				else {
					listJobTypes = find(hql, parentId);
				}
				redisTemplate.opsForValue().set(key, listJobTypes);
			}
			catch (Exception e) {
				log.error("获取父类ID为{}的职位类别列表出错.", parentId);
			}
		}
		
		return listJobTypes;
	}
	
	public String getJobNameById(Integer id) {
		String key = RedisConstants.KEY_JOBTYPE_SIGNLE_NAME + "_" + id;
		
		String jobTypeName = null;
		try {
			jobTypeName = stringRedisTemplate.opsForValue().get(key);
		}
		catch (Exception e) {
			log.error("获取职位类别列表出错.");
		}
		if (StringUtils.isBlank(jobTypeName)) {
			try {
				jobTypeName = this.get(id).getName();
				stringRedisTemplate.opsForValue().set(key, jobTypeName);
			}
			catch (Exception e) {
				log.error("获取职位类别列表出错.");
			}
		}
		
		return jobTypeName;
	}
}
